#region Copyright (c) 2007 Mikko Salmi, Contributors
/*
 *
 * Copyright (c) 2007 Mikko Salmi, Contributors
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT 
 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
 * 
*/
#endregion // Copyright

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

using Microsoft.SharePoint;

namespace CodePlex.WebParts
{
    public static class DocumentRating
    {
        public static void Save(int rating, string feedback, string document)
        {
            SPSite site = SPContext.Current.Site;
            SPWeb web = SPContext.Current.Web;
            string userName = web.CurrentUser.LoginName;

            document = document.Replace("?PageView=Shared", string.Empty);
            document = document.Replace("#", string.Empty);

            if (!listExists(web.Lists, "Ratings"))
            {
                createList(web);
            }

            SPList ratingsList = web.Lists["Ratings"];

            SPQuery q = new SPQuery();
            q.Query = "<Where><And><Eq><FieldRef Name=\"Title\" />" +
                "<Value Type = \"Text\">" + document + "</Value></Eq>" +
                "<Eq><FieldRef Name=\"Rater\" />" +
                "<Value Type = \"Text\">" + userName + "</Value></Eq></And></Where>";
            q.ViewFields = "<FieldRef Name=\"Rating\"/>";
            SPListItemCollection queryResults = ratingsList.GetItems(q);

            if (queryResults.Count == 0)
            {
                SPListItem item = ratingsList.Items.Add();
                item["Title"] = document;
                item["Rating"] = rating;
                item["Feedback"] = feedback;
                item["Rater"] = userName;
                item.Update();
            }
            else
            {
                SPListItem item = queryResults[0];
                item["Title"] = document;
                item["Rating"] = rating;
                item["Feedback"] = feedback;
                item["Rater"] = userName;
                item.Update();
            }

            web.Close();
            web.Dispose();

            site.Close();
            site.Dispose();
        }

        private static bool listExists(SPListCollection collection, string name)
        {
            foreach (SPList list in collection)
            {
                if (list.Title == "Ratings")
                {
                    return true;
                }
            }

            return false;
        }

        private static void createList(SPWeb web)
        {
            string listName = "Ratings";

            // Add new list.
            web.Lists.Add(listName, string.Empty, SPListTemplateType.GenericList);

            // Add fields.
            web.Lists[listName].Fields.Add("Title", SPFieldType.Text, false);
            web.Lists[listName].Fields.Add("Rating", SPFieldType.Number, false);
            web.Lists[listName].Fields.Add("Feedback", SPFieldType.Text, false);
            web.Lists[listName].Fields.Add("Rater", SPFieldType.Text, false);

            // Create also default view with new fields.
            SPView defaultView = web.Lists[listName].DefaultView;
            defaultView.ViewFields.DeleteAll();
            defaultView.ViewFields.Add("Title");
            defaultView.ViewFields.Add("Rating");
            defaultView.ViewFields.Add("Feedback");
            defaultView.ViewFields.Add("Rater");
            defaultView.Update();
        }

        public static double GetRating(string document)
        {
            SPWeb web = SPContext.Current.Web;

            if (!listExists(web.Lists, "Ratings"))
            {
                createList(web);
            }

            SPList ratingsList = web.Lists["Ratings"];

            document = document.Replace("?PageView=Shared", string.Empty);
            document = document.Replace("#", string.Empty);

            SPQuery q = new SPQuery();
            q.Query = "<Where><Eq><FieldRef Name=\"Title\" />" +
                "<Value Type = \"Text\">" + document + "</Value></Eq></Where>";
            q.ViewFields = "<FieldRef Name=\"Rating\"/>";
            SPListItemCollection queryResults = ratingsList.GetItems(q);
            if (queryResults.Count > 0)
            {
                DataTable dt = queryResults.GetDataTable();
                return (double)dt.Compute("AVG(Rating)", "");
            }
            else
            {
                return 0;
            }
        }

        public static double GetRating(string document, string userName)
        {
            SPWeb web = SPContext.Current.Web;

            if (!listExists(web.Lists, "Ratings"))
            {
                createList(web);
            }

            SPList ratingsList = web.Lists["Ratings"];

            document = document.Replace("?PageView=Shared", string.Empty);
            document = document.Replace("#", string.Empty);

            SPQuery q = new SPQuery();
            q.Query = "<Where><And><Eq><FieldRef Name=\"Title\" />" +
                "<Value Type = \"Text\">" + document + "</Value></Eq>" +
                "<Eq><FieldRef Name=\"Rater\" />" +
                "<Value Type = \"Text\">" + userName + "</Value></Eq></And></Where>";
            q.ViewFields = "<FieldRef Name=\"Rating\"/>";
            SPListItemCollection queryResults = ratingsList.GetItems(q);
            if (queryResults.Count > 0)
            {
                DataTable dt = queryResults.GetDataTable();
                return (double)dt.Compute("AVG(Rating)", "");
            }
            else
            {
                return 0;
            }
        }
    }
}
